package edu.nf.test.service;

import edu.nf.test.entity.User;
import edu.nf.test.mapper.UserMapper;
import edu.nf.test.util.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author CSY
 * @date 2025 - 04 - 23
 */
@Service
public class UserService {
    public List<User> listUser(){
        return MyBatisUtils.getSqlSession()
                .getMapper(UserMapper.class)
                .listUser();
    }

    public User getUser(String name,Integer age){
        return MyBatisUtils.getSqlSession()
                .getMapper(UserMapper.class)
                .getUser(name,age);
    }

    public List<User> listUserByParam(User user){
        return MyBatisUtils.getSqlSession()
                .getMapper(UserMapper.class)
                .listUserByParam(user);
    }

    public List<User> listUsersByIds(List<Integer> ids){
        return MyBatisUtils.getSqlSession()
                .getMapper(UserMapper.class)
                .listUsersByIds(ids);
    }

    public void update(User user){
        MyBatisUtils.getSqlSession()
                .getMapper(UserMapper.class)
                .update(user);
    }

    public void insert(User user){
        MyBatisUtils.getSqlSession()
                .getMapper(UserMapper.class)
                .insert(user);
    }

    public void insertMore(List<User> users){
        SqlSession sqlSession = MyBatisUtils.getSqlSession(false);
        try{
            sqlSession.getMapper(UserMapper.class).insertMore(users);
            sqlSession.commit();
        }catch(Exception e){
            sqlSession.rollback();
            throw new RuntimeException(e);
        }finally {
            sqlSession.close();
        }
    }

    public void delete(Integer id){
        MyBatisUtils.getSqlSession()
                .getMapper(UserMapper.class)
                .delete(id);
    }

    public void deleteMore(List<Integer> ids){
        SqlSession sqlSession = MyBatisUtils.getSqlSession(false);
        try{
            sqlSession.getMapper(UserMapper.class).deleteMore(ids);
            sqlSession.commit();
        }catch (Exception e){
            sqlSession.rollback();
            throw new RuntimeException(e);
        }finally {
            sqlSession.close();
        }
    }
}
